﻿using System;
using System.Web.UI.WebControls;
using Business;
using System.Data;
using System.Web.Security;

public partial class admin_View_Client : System.Web.UI.Page
{
    //Create new encryption object
    private Encryption objenc = new Encryption();
    private int client_id;

    protected void Page_Load(object sender, EventArgs e)
    {
        client_id = Int32.Parse((String) Request.QueryString["client_id"]);
        if (!IsPostBack)
        {
            loadUsers();
        }
    }

    protected void CreateAccountButton_Click(object sender, EventArgs e)
    {
        Label clientNameLabel = FormViewClient.FindControl("clientNameLabel") as Label;
        string client_id = objenc.EncodeUrl(FormViewClient.SelectedValue.ToString());
        string clientName = objenc.EncodeUrl(clientNameLabel.Text);
        Server.Transfer("Create_User.aspx?client_id=" + client_id + "&clientName=" + clientName);
    }

    protected void loadUsers()
    {
        var dcryp = new Decryption();
        var query = "SELECT user_id,username, password,role,email FROM Users u where u.client_id='" + client_id + "'";
        var objcon = new CreateConn();
        var dt = objcon.SQLConnDataTable(query);
        if (dt != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                string password = dr["password"].ToString();
                dr["password"] = dcryp.DecryptString(password);
            }
            GridView_users.DataSource = dt;
            GridView_users.DataBind();
        }
    }

    protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView_users.EditIndex = e.NewEditIndex;
        this.loadUsers();
        GridView_users.DataBind();
    }

    protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView_users.EditIndex = -1;
        GridView_users.DataBind();
    }

    protected void user_updating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView_users.Rows[e.RowIndex];
        HiddenField hdn = row.FindControl("hfID") as HiddenField;
        string test = hdn.Value;
        string name = ((TextBox) (row.Cells[0].Controls[0])).Text;
        string psw = ((TextBox) (row.Cells[1].Controls[0])).Text;
        psw = new Encryption().EncryptString(psw);
        DropDownList role_lsit = (DropDownList) row.Cells[2].FindControl("role_dropdownlist");
        string role = role_lsit.SelectedValue;

        string query = "Update Users set username='" + name + "',password='"
                       + psw + "',role='" + role + "' WHERE user_id='" + test + "'";

        var objcon = new CreateConn();
        objcon.SQLConnDataTable(query);
        GridView_users.EditIndex = -1;
        loadUsers();
    }

    protected void client_updating(object sender, FormViewUpdateEventArgs e)
    {
        var tb = (TextBox) FormViewClient.FindControl("date_registeredTextBox");

        string text = tb.Text;
        var dateInfo = new System.Globalization.DateTimeFormatInfo();

        dateInfo.ShortDatePattern = "dd/MM/yyyy";
        if (text != string.Empty)
        {
            var dt = Convert.ToDateTime(text, dateInfo);
            e.NewValues["date_registered"] = dt.Date.ToString();
        }
        var tb_expired = (TextBox) FormViewClient.FindControl("licenced_expiredTextBox");
        string text_expired = tb_expired.Text;
        if(!text_expired.Equals(string.Empty))
        {
            var dt_expired = Convert.ToDateTime(text_expired, dateInfo);
            e.NewValues["licenced_expired"] = dt_expired.Date.ToString();
        }
    }

    protected void client_ItemUpdated(Object sender, FormViewUpdatedEventArgs e)
    {
        if (e.Exception == null)
        {
            if (e.AffectedRows == 1)
            {
                String keyFieldValue = e.Keys["client_id"].ToString();
                Response.Write("Record " + keyFieldValue +
                               " updated successfully. ");
            }
        }
        else
        {
            Response.Write(e.Exception.Message);
            e.ExceptionHandled = true;
            e.KeepInEditMode = true;
        }
    }

    protected void GridViewSites_SelectedIndexChanged(object sender, EventArgs e)
    {
        string site_id = GridViewSites.SelectedDataKey.Value.ToString();
        Server.Transfer("View_Site.aspx?site_id=" + site_id);
    }

    protected void CreateSiteButton_Click(object sender, EventArgs e)
    {
        string client_id = objenc.EncodeUrl(FormViewClient.SelectedValue.ToString());
        Server.Transfer("Create_Site.aspx?client_id=" + client_id);
    }

    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Session.Contents.Remove("UserDetails");
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
        Response.Redirect("../Default.aspx");
    }
}